package com.songlanyun.modules.rights.controller.api;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.songlanyun.common.annotation.RepeatSubmit;
import com.songlanyun.common.enums.HouniaoConstant;
import com.songlanyun.common.enums.RightsOrderConstant;
import com.songlanyun.common.supplychainapi.aftersale.ApiAfterSaleCommon;
import com.songlanyun.common.supplychainapi.aftersale.model.AfterSaleInfo;
import com.songlanyun.common.supplychainapi.aftersale.model.BeforeCheck;
import com.songlanyun.common.utils.HouniaoApiUtil;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;
import com.songlanyun.modules.account.controller.common.AbstractApiController;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.service.ChildOrderService;
import com.songlanyun.modules.order.service.OrderService;
import com.songlanyun.modules.rabbitmq.mq.producer.SendOrderOrRightsOrderMsgService;
import com.songlanyun.modules.rights.entity.RightsOrder;
import com.songlanyun.modules.rights.entity.RightsOrderShipRecord;
import com.songlanyun.modules.rights.model.dto.ApplyOrderRightsDTO;
import com.songlanyun.modules.rights.model.dto.ApplyThirdOrderRightsCheckDTO;
import com.songlanyun.modules.rights.model.dto.RightsOrderShipDTO;
import com.songlanyun.modules.rights.model.vo.RightsMoneyVo;
import com.songlanyun.modules.rights.service.RightsOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;


/**
 * 销售系统中的维权单（前期可能只做统一维权，不过这样不好）
 *
 * @author lubo
 * @email sunlightcs@gmail.com
 * @date 2020-11-23 13:45:42
 */
@RestController
@RequestMapping("api/rights")
public class RightsOrderApiController extends AbstractApiController {
    @Autowired
    private RightsOrderService rightsOrderService;

    @Autowired
    private SendOrderOrRightsOrderMsgService sendOrderOrRightsOrderMsgService;

    @Autowired
    private ApiAfterSaleCommon apiAfterSaleCommon;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ChildOrderService childOrderService;

    @Autowired
    private HouniaoApiUtil houniaoApiUtil;

    @Autowired
    private GoodsService goodsService;

    /**
     * 退货流程：
     * 退货申请➡商家同意➡买家发货➡商家确认收货➡打款
     * 退货申请➡商家不同意
     *
     * 退货条件：
     * 必须后收货后才能退货。

     * 退款流程：
     * 退款申请➡商家同意➡打款
     * 退款申请➡商家不同意
     *
     * 退款条件：
     * 支付后即可申请退款。未发货只能全部退款，待收货不能退款，收货可退款。
     *
     * 打款：打款由商家提交退款申请，从平台微信商户/支付宝商户中退相应金额的款项，同时扣除商家所得。
     */


    /**
     * 会员查看自己的所有维权订单
     * params参数说明
     * rights_type 1仅退款,2退款退货
     * order_code 订单编号
     * pay_refund_code 支付退款单编号
     * refund_status 交易状态（0已下单,待支付，1待发货（待备货） 3,"待收货（待自提）",5交易完成
     * operate_status 维权订单操作状态（0申请，1同意，2买家已发货，3商家已收到退货商品,4商家发起退款支付，5已支付退款,6拒绝，7自动关闭,8主动撤消
     * page 当前第几页（默认第一页）
     * limit 每页多少条 （默认每页10条）
     */
    @GetMapping("/page")
    //@RequiresPermissions("rights:salerightsorder:list")
    public R page(@RequestParam Map<String, Object> params){
        params.put("user_id",getUserId(true));
        params.put("client",getClient());
        Integer areaFeature = MapUtil.getInt(params, "area_feature");
        areaFeature = areaFeature == null ? 0 : areaFeature;
        params.put("area_feature", areaFeature);

        PageUtils page = rightsOrderService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 加载主维权订单
     */
    @GetMapping("/main/{orderId}")
    //@RequiresPermissions("rights:salerightsorder:info")
    public R mainOrderRightOrder(@PathVariable("orderId") Long orderId){
		RightsOrder rightsOrder = rightsOrderService.loadMainRightsOrder(getUserId(true),orderId,false);
		if(rightsOrder==null)
        {
            return R.ok().put("data", null);
        }
        rightsOrder.loadRightsChildOrders();
        rightsOrder.loadRightsOrderOperateRecords();;
        return R.ok().put("data", rightsOrder);
    }


    /**
     * 加载子维权订单
     */
    @GetMapping("/child/{orderId}/{childOrderId}")
    //@RequiresPermissions("rights:salerightsorder:info")
    public R childOrderRightOrder(@PathVariable("orderId") Long orderId,@PathVariable("childOrderId") Long childOrderId){
        RightsOrder rightsOrder = rightsOrderService.loadChildRightsOrder(getUserId(true),orderId,childOrderId,false);
        if(rightsOrder==null)
        {
            return R.ok().put("data", null);
        }
        rightsOrder.loadRightsChildOrders();
        rightsOrder.loadRightsOrderOperateRecords();
        return R.ok().put("data", rightsOrder);
    }

    /**
     * 加载维权订单
     */
    @GetMapping("/info/{id}")
    //@RequiresPermissions("rights:salerightsorder:info")
    public R rightOrderInfo(@PathVariable("id") Long id){
        RightsOrder rightsOrder = rightsOrderService.loadByUserAndId(getUserId(true),id,false);
        if(rightsOrder==null)
        {
            return R.ok().put("data", null);
        }
        rightsOrder.loadRightsChildOrders();
        rightsOrder.loadRightsOrderOperateRecords();
        rightsOrder.loadRightsOrderShipRecord();

        return R.ok().put("data", rightsOrder);
    }

    /**
     * 商家取消维权
     * @param rightsId
     * @return
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/cancel/{userId}/{rightsId}")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R cancel(@PathVariable("userId") Long userId, @PathVariable("rightsId") Long rightsId){
        RightsOrder rightsOrder = rightsOrderService.cancel(userId,rightsId);
        return R.ok().put("data",rightsOrder);
    }

    /**
     * 获得主订单维权可以最多可以退多少钱
     */
    @PostMapping("/main/able-refund-money")
    //@RequiresPermissions("rights:salerightsorder:info")
    public R getMoneyByMainRights(@RequestBody ApplyOrderRightsDTO dto){
        dto.setUserId(getUserId(true));
        RightsMoneyVo vo =  rightsOrderService.getMoneyByMainRights(getUserId(true),dto.getOrderId());

        return R.ok().put("data", vo);
    }

    /**
     * 获得子订单维权可以最多可以退多少钱
     */
    @PostMapping("/child/able-refund-money")
    //@RequiresPermissions("rights:salerightsorder:info")
    public R getMoneyByChildRights(@RequestBody ApplyOrderRightsDTO dto){
        dto.setUserId(getUserId(true));
        RightsMoneyVo vo = rightsOrderService.getMoneyByChildRights(dto);
        return R.ok().put("data", vo);
    }


    /**
     * 会员发起主订单维权
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/apply/order")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R orderApply(@RequestBody ApplyOrderRightsDTO dto){
        dto.setUserId(getUserId(true));
		RightsOrder rightsOrder = rightsOrderService.applyOrder(dto);
        sendOrderOrRightsOrderMsgService.applyRightsOrderSuccessSendMsg(rightsOrder);
        return R.ok().put("data",rightsOrder);
    }

    /**
     * 会员发起子订单维权
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/apply/child")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R childApply(@RequestBody ApplyOrderRightsDTO dto){
        dto.setUserId(getUserId(true));
        dto.setRightsOperatePerson(RightsOrderConstant.RightsOperatePerson.USER.getCode());
        RightsOrder rightsOrder = rightsOrderService.applyChildOrder(dto);
        if(!rightsOrder.getThird()) {
            sendOrderOrRightsOrderMsgService.applyRightsOrderSuccessSendMsg(rightsOrder);
        }
        return R.ok().put("data",rightsOrder);
    }

    /**
     * 会员退货订单发货
     * @param dto
     * @return
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/ship")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R ship(@RequestBody RightsOrderShipDTO dto){
        RightsOrder rightsOrder = rightsOrderService.ship(getUserId(true),dto);
        if(!rightsOrder.getThird()) {
            sendOrderOrRightsOrderMsgService.rightsShipSendMsg(rightsOrder);
        }
        return R.ok().put("data",rightsOrder);
    }

    /**
     * 会员主动取消维权
     * @param rightsId
     * @return
     */
    @RepeatSubmit(value = "5")
    @PostMapping("/cancel/{rightsId}")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R cancel(@PathVariable("rightsId") Long rightsId){
        RightsOrder rightsOrder = rightsOrderService.cancel(getUserId(true),rightsId);
        return R.ok().put("data",rightsOrder);
    }


    /**
     * 会员查看退货物流跟踪
     */
    @GetMapping("/express/select/{rightsId}")
    //@RequiresPermissions("ship:saleorderpackage:save")
    public R expressSelect(@PathVariable("rightsId") Long rightsId){
        RightsOrderShipRecord rightsOrderShipRecord = rightsOrderService.expressSelect(rightsId);

        if(rightsOrderShipRecord==null)
        {
            return R.ok().put("data",null);
        }

        if(StringUtils.isBlank(rightsOrderShipRecord.getQueryResult()))
        {
            return R.ok().put("data",null);
        }

        JSONObject jsonObject = JSONObject.parseObject(rightsOrderShipRecord.getQueryResult());
        return R.ok().put("data",jsonObject);
    }

    /**
     * 第三方售后前置校验V2
     */
    @PostMapping("/third/beforeCheck")
    //@RequiresPermissions("rights:salerightsorder:save")
    public R beforeCheck(@RequestBody ApplyThirdOrderRightsCheckDTO dto){
        Order order = orderService.loadById(dto.getOrderId(), true);
//         第三方订单校验
        if(order.getThird()) {
//            ChildOrder childOrder = childOrderService.loadByOrderAndChildId(dto.getOrderId(), dto.getChildOrderId(), true);
//            BeforeCheckParam build = BeforeCheckParam.builder()
//                    .orderSn(order.getOrderCode()).sku(childOrder.getThirdSkuId()).build();
//            BeforeCheck beforeCheck = apiAfterSaleCommon.beforeCheck(build);
            BeforeCheck beforeCheck = new BeforeCheck();
            BeforeCheck.ServiceType serviceType = new BeforeCheck.ServiceType();
            serviceType.setCode("40");
            serviceType.setName("退款");
            beforeCheck.setServiceType(new BeforeCheck.ServiceType[]{serviceType});
//            beforeCheck.setServiceType(new BeforeCheck.ServiceType[]{serviceType});
//            beforeCheck.setNum(0);
            return R.ok().put("data",beforeCheck);
        }
        return R.ok();
    }

    /**
     * 第三方售后订单详情(主要可以用来取商家的收货地址)
     * @param rightsId
     * @return
     */
    @GetMapping("/third/info/{rightsId}")
    public R thirdInfo(@PathVariable("rightsId") Long rightsId){
        RightsOrder rightsOrder = rightsOrderService.loadById(rightsId, true);
        if(!rightsOrder.getThird()) {
            return R.ok();
        }
//        AfterSaleInfo afterSaleInfo = apiAfterSaleCommon.afterSaleInfo(rightsOrder.getThirdRightsId().toString());
        AfterSaleInfo afterSaleInfo = new AfterSaleInfo();
        return R.ok().put("data",afterSaleInfo);
    }

    /**
     * 获取候鸟的售后原因列表
     * @return 候鸟的售后原因列表
     */
    @GetMapping("/third/afterSaleSeasons")
    public R getAfterSaleReasons(){
        JSONObject req = new JSONObject();
        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.AFTER_SALE_GET_REASON.getUrl());
        JSONArray data = js.getJSONArray("data");
        return R.ok().put("data", data);
    }

}
